package com.lqian.demo01;

import com.lqian.utils.SleepHelper;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 如果你想打断一个锁的争抢过程，用ReentrantLock锁
 * 如果你想允许interrupt()去干扰到它的话，用lock.lockInterruptibly方法
 */
public class

Interrupt_and_LockInterruptibly {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            lock.lock();
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
            System.out.println("t1 end..");
        });
        t1.start();
        SleepHelper.sleepSeconds(1);

        Thread t2 = new Thread(()->{
            try {
                lock.lockInterruptibly(); //可以被interrupt
                // t2 被干扰 抛出异常 抛出异常之后 是继续执行还是决定继续睡或者是别的逻辑
                // 由你在catch中处理
                //lockInterruptibly（）的功能，可以中断争夺锁的操作，抢锁的时候会check是否被中断，中断直接抛出异常，退出抢锁。
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println("t2 end..");
        });
        t2.start();
        SleepHelper.sleepSeconds(1);
        t2.interrupt();
    }
}
